const express = require('express');
const router = express.Router();
const db = require('../db');
const {md5} = require('utility');
const jwt = require('jsonwebtoken');

//验证
router.use((req,res,next)=>{
    // console.log(req.body);
    let {username,password} =req.body;
    if(!/^[a-zA-Z][0-9a-zA-Z_]{1,9}$/.test(username)){
        next('账户名必须英文字母开头且长度为2-10位')
    }else if(!/^\S{6,12}$/.test(password)){
        next('密码必须是6到12位且不能有空格')
    }else{
        next();
    }
})

//注册
router.post('/reguser',(req,res)=>{
    // console.log(req.body);

    //获取请求体
    let {username,password} = req.body;

    db(`select * from user where  username = "${username}"`,(err,result)=>{
        if(err) throw err;
        // console.log(result);
        if(result.length > 0){
            res.send({status:1,message:'用户名已存在'});
        }else{

             password = md5(password);

            db(`insert into user set username="${username}",password="${password}"`,(err,result)=>{
                if(err) throw err;
                res.send({status:0,message:'注册成功'});
            })
        }
    })   
})

//登陆
router.post('/login',(req,res)=>{

    let {username,password} = req.body;

    //因为前面加密过,所以现在输入的密码,也要加密才能匹配的到
    password = md5(password);

    db(`select * from user where username = "${username}" and password = "${password}"`,(err,result)=>{
        if(err) throw err;
        // console.log(result);
        //查询的到,就代表账号密码正确,登陆成功,否则反之
        if(result.length > 0){
            //创建一个token   'Bearer' 是一个认证
            let token = 'Bearer ' + jwt.sign({id:result[0].id},'asdad',{expiresIn:'2h'});

            res.send({status : 0,message:'登陆成功',token});
            
        }else{
            res.send({status:1,message:'账号或者密码不正确!!!'});
        }
    })
})

router.use((err,req,res,next)=>{

    res.send({status:1,message:err});
    
})

module.exports = router;